import 'dart:math' as math;

import 'package:faker/models/article.dart';
import 'package:faker/provider/favorite_rss_provider.dart';
import 'package:faker/res/style.dart';
import 'package:faker/utils/toast_util.dart';
import 'package:faker/widgets/base_widget.dart';
import 'package:faker/widgets/item_article_list.dart';
import 'package:faker/widgets/loading_dialog.dart';
import 'package:faker/widgets/refresh_helper.dart';
import 'package:flutter/material.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../i18n/i18n.dart';

class FavRssScreen extends BaseWidget {
  @override
  _FavRssScreenState createState() => _FavRssScreenState();

  @override
  BaseWidgetState<BaseWidget> attachState() {
    // TODO: implement attachState
    return null;
  }
}

class _FavRssScreenState extends BaseWidgetState<FavRssScreen> {
  ///浮动标题
  bool floating = false;
  bool snap = false;
  bool pinned = false;

  /// 是否显示悬浮按钮
  bool _isShowFAB = true;

  List<Article> articleitems = new List();

  /// listview 控制器
  ScrollController _scrollController = new ScrollController();

  /// 下拉刷新控制器
  RefreshController _refreshController =
      new RefreshController(initialRefresh: false);

  /// ListView Item 左右滑动;
  final SlidableController slidableController = SlidableController();

  int cnt = 0;

  /// getRss Data
  Future getRssData() async {
    articleitems.clear();
    FavRssProvider provider = new FavRssProvider();
    List list = await provider.getAllFavRssProvider();
    if (list.length > 0) {
      print(list.length);
      //数据库有数据
      showContent().then((value) {
        _refreshController.refreshCompleted(resetFooterState: true);
        setState(() {
          articleitems.addAll(Article.fromMapList(list));
          print(articleitems.length);
        });
      });
    } else
      showEmpty();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    showLoading().then((value) {
      getRssData();
    });

    _scrollController.addListener(() {
      /// 滑动到底部，加载更多
      if (_scrollController.position.pixels ==
          _scrollController.position.maxScrollExtent) {
        // getMoreNoTodoList();
      }
      if (_scrollController.offset < 200 && _isShowFAB) {
        setState(() {
          _isShowFAB = false;
        });
      } else if (_scrollController.offset >= 200 && !_isShowFAB) {
        setState(() {
          _isShowFAB = true;
        });
      }
    });
  }

  @override
  void initState() {
    super.initState();
    setAppBarVisible(true);
  }

  @override
  Widget build(BuildContext context) {
    return Container(
        height: MediaQuery.of(context).size.height,
        color: Theme.of(context).backgroundColor,
        child: SmartRefresher(
          enablePullDown: true,
          enablePullUp: false,
          header: MaterialClassicHeader(),
          footer: RefreshFooter(),
          controller: _refreshController,
          onRefresh: getRssData,
          onLoading: getRssData,
          child: CustomScrollView(
            physics: ScrollPhysics(),
            slivers: <Widget>[
              SliverPersistentHeader(
                pinned: false,
                floating: true,
                delegate: _SliverAppBarDelegate(
                  minHeight: 0.0,
                  maxHeight: 120.0,
                  child: Container(
                    decoration: BoxDecoration(
                      borderRadius:
                          new BorderRadius.all(new Radius.circular(5.0)),
                      image: DecorationImage(
                        image: AssetImage("assets/images/011.jpg"),
                        fit: BoxFit.cover,
                      ),
                    ),
                    alignment: Alignment(0.0, 0.4),
                    child: Text(
                      S.of(context).favourite,
                      textAlign: TextAlign.center,
                      style: TextStyle(
                        color: Theme.of(context).textSelectionColor,
                        fontSize: 46.0,
                        fontFamily: fontName,
                        letterSpacing: 1.0,
                        decoration: TextDecoration.none,
                      ),
                    ),
                  ),
                ),
              ),
              SliverToBoxAdapter(
                child: SizedBox(
                  height: 20,
                  child: Container(
                    color: Theme.of(context).backgroundColor,
                    width: 20.0,
                  ),
                ),
              ),
              SliverList(
                delegate: SliverChildBuilderDelegate(
                  (BuildContext context, int index) {
                    return itemView(context, index);
                  },
                  childCount: articleitems.length,
                ),
              ),
            ],
          ),
        ));
  }

  Widget itemView(BuildContext context, int index) {
    Article item = articleitems[index];
    return ItemArticleList(
      item: item,
      delete: (guid) async {
        FavRssProvider provider = new FavRssProvider();
        await provider.delete(guid);
        T.show(msg: S.of(context).successDelete);
        getRssData();
      },
    );
  }

  @override
  AppBar attachAppBar() {
    // TODO: implement attachAppBar
    return null;
  }

  @override
  void dispose() {
    _refreshController.dispose();
    _scrollController.dispose();
    super.dispose();
  }

  /// 显示Loading
  _showLoading(BuildContext context) {
    showDialog(
        context: context,
        barrierDismissible: false,
        builder: (_) {
          return new LoadingDialog(
            outsideDismiss: false,
            loadingText: S.of(context).onLoading,
          );
        });
  }

  @override
  Widget attachContentWidget(BuildContext context) {
    // TODO: implement attachContentWidget
    return null;
  }

  @override
  void onClickErrorWidget() {
    // TODO: implement onClickErrorWidget
  }
}

class _SliverAppBarDelegate extends SliverPersistentHeaderDelegate {
  _SliverAppBarDelegate({
    @required this.minHeight,
    @required this.maxHeight,
    @required this.child,
  });

  final double minHeight;
  final double maxHeight;
  final Widget child;

  @override
  double get minExtent => minHeight;

  @override
  double get maxExtent => math.max(maxHeight, minHeight);

  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    return new SizedBox.expand(child: child);
  }

  @override
  bool shouldRebuild(_SliverAppBarDelegate oldDelegate) {
    return maxHeight != oldDelegate.maxHeight ||
        minHeight != oldDelegate.minHeight ||
        child != oldDelegate.child;
  }
}
